<?php

namespace addons\wechatopen;

use app\common\library\Menu;
use EasyWeChat\MiniProgram\Application as MiniProgram;
use EasyWeChat\OfficialAccount\Application as OfficialAccount;
use EasyWeChat\OpenPlatform\Application as OpenPlatform;
use EasyWeChat\Payment\Application as Payment;
use EasyWeChat\Work\Application as Work;
use Illuminate\Container\Container;
use think\Addons;
use think\Cache;
use think\Loader;
use app\admin\model\wechatopen\Wechatopen as wechatopenModel;
use think\Request;
use uctoo\ThinkEasyWeChat\Behavior\AppInit;
use uctoo\ThinkEasyWeChat\CacheBridge;
use app\admin\model\wechatopen\Applet;

/**
 * 微信第三方平台插件
 */
class Wechatopen extends Addons
{
    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu = [
            [
                'name'    => 'wechatopen',
                'title'   => '微信第三方平台',
                'icon'    => 'fa fa-wechat',
                'sublist' => [
                    [
                        'name'    => 'wechatopen/wechatopen',
                        'title'   => '微信开放平台',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'wechatopen/wechatopen/getappletid', 'title' => 'GetAppletid'],
                            ['name' => 'wechatopen/wechatopen/checkappletid', 'title' => 'CheckAppletId'],
                            ['name' => 'wechatopen/wechatopen/index', 'title' => '查看'],
                            ['name' => 'wechatopen/wechatopen/recyclebin', 'title' => '回收站'],
                            ['name' => 'wechatopen/wechatopen/add', 'title' => '添加'],
                            ['name' => 'wechatopen/wechatopen/edit', 'title' => '编辑'],
                            ['name' => 'wechatopen/wechatopen/del', 'title' => '删除'],
                            ['name' => 'wechatopen/wechatopen/destroy', 'title' => '真实删除'],
                            ['name' => 'wechatopen/wechatopen/restore', 'title' => '还原'],
                            ['name' => 'wechatopen/wechatopen/multi', 'title' => '批量更新'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/applet',
                        'title'   => '微信应用管理',
                        'icon'    => 'fa fa-comments-o',
                        'sublist' => [
                            ['name' => 'wechatopen/applet/index', 'title' => '查看'],
                            ['name' => 'wechatopen/applet/add', 'title' => '添加'],
                            ['name' => 'wechatopen/applet/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/applet/del', 'title' => '删除'],
                            ['name' => 'wechatopen/applet/multi', 'title' => '批量更新'],
                            ['name' => 'wechatopen/applet/set_applet', 'title' => '切换应用'],
                            ['name' => 'wechatopen/applet/authpage', 'title' => '第三方授权'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/autoreply',
                        'title'   => '自动回复管理',
                        'icon'    => 'fa fa-reply-all',
                        'sublist' => [
                            ['name' => 'wechatopen/autoreply/index', 'title' => '查看'],
                            ['name' => 'wechatopen/autoreply/add', 'title' => '添加'],
                            ['name' => 'wechatopen/autoreply/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/autoreply/del', 'title' => '删除'],
                            ['name' => 'wechatopen/autoreply/multi', 'title' => '批量更新'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/config',
                        'title'   => '配置管理',
                        'icon'    => 'fa fa-cog',
                        'sublist' => [
                            ['name' => 'wechatopen/config/index', 'title' => '查看'],
                            ['name' => 'wechatopen/config/add', 'title' => '添加'],
                            ['name' => 'wechatopen/config/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/config/del', 'title' => '删除'],
                            ['name' => 'wechatopen/config/multi', 'title' => '批量更新'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/menu',
                        'title'   => '菜单管理',
                        'icon'    => 'fa fa-list',
                        'sublist' => [
                            ['name' => 'wechatopen/menu/index', 'title' => '查看'],
                            ['name' => 'wechatopen/menu/add', 'title' => '添加'],
                            ['name' => 'wechatopen/menu/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/menu/del', 'title' => '删除'],
                            ['name' => 'wechatopen/menu/sync', 'title' => '同步'],
                            ['name' => 'wechatopen/menu/multi', 'title' => '批量更新'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/response',
                        'title'   => '资源管理',
                        'icon'    => 'fa fa-list-alt',
                        'sublist' => [
                            ['name' => 'wechatopen/response/index', 'title' => '查看'],
                            ['name' => 'wechatopen/response/add', 'title' => '添加'],
                            ['name' => 'wechatopen/response/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/response/del', 'title' => '删除'],
                            ['name' => 'wechatopen/response/select', 'title' => '选择'],
                            ['name' => 'wechatopen/response/multi', 'title' => '批量更新'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/admin_applet',
                        'title'   => '管理员当前选中微应用',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'wechatopen/admin_applet/index', 'title' => '查看'],
                            ['name' => 'wechatopen/admin_applet/add', 'title' => '添加'],
                            ['name' => 'wechatopen/admin_applet/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/admin_applet/del', 'title' => '删除'],
                            ['name' => 'wechatopen/admin_applet/select', 'title' => '选择'],
                            ['name' => 'wechatopen/admin_applet/multi', 'title' => '批量更新'],
                        ]
                    ],
                    [
                        'name'    => 'wechatopen/wechat_user',
                        'title'   => '微信用户管理',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'wechatopen/wechat_user/index', 'title' => '查看'],
                            ['name' => 'wechatopen/wechat_user/add', 'title' => '添加'],
                            ['name' => 'wechatopen/wechat_user/edit', 'title' => '修改'],
                            ['name' => 'wechatopen/wechat_user/del', 'title' => '删除'],
                            ['name' => 'wechatopen/wechat_user/select', 'title' => '选择'],
                            ['name' => 'wechatopen/wechat_user/multi', 'title' => '批量更新'],
                        ]
                    ]
                ]
            ],
            [
                'name'    => 'miniapp',
                'title'   => '微信小程序',
                'icon'    => 'fa fa-html5 fa-fw',
                'sublist' => [
                    [
                        'name'    => 'miniapp/version',
                        'title'   => '小程序版本管理',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'miniapp/version/import', 'title' => 'Import'],
                            ['name' => 'miniapp/version/index', 'title' => '查看'],
                            ['name' => 'miniapp/version/add', 'title' => '添加'],
                            ['name' => 'miniapp/version/edit', 'title' => '编辑'],
                            ['name' => 'miniapp/version/del', 'title' => '删除'],
                            ['name' => 'miniapp/version/multi', 'title' => '批量更新'],
                            ['name' => 'miniapp/version/commit', 'title' => '上传代码'],
                            ['name' => 'miniapp/version/getqrcode', 'title' => '预览二维码'],
                            ['name' => 'miniapp/version/submitaudit', 'title' => '提交审核'],
                            ['name' => 'miniapp/version/release', 'title' => '提交发布'],
                            ['name' => 'miniapp/version/qrcode', 'title' => '体验版二维码页面'],
                        ]
                    ],
                    [
                        'name'    => 'miniapp/cloud',
                        'title'   => '小程序云开发',
                        'icon'    => 'fa fa-circle-o',
                        'sublist' => [
                            ['name' => 'miniapp/cloud/import', 'title' => 'Import'],
                            ['name' => 'miniapp/cloud/index', 'title' => '查看'],
                            ['name' => 'miniapp/cloud/recyclebin', 'title' => '回收站'],
                            ['name' => 'miniapp/cloud/add', 'title' => '添加'],
                            ['name' => 'miniapp/cloud/edit', 'title' => '编辑'],
                            ['name' => 'miniapp/cloud/del', 'title' => '删除'],
                            ['name' => 'miniapp/cloud/destroy', 'title' => '真实删除'],
                            ['name' => 'miniapp/cloud/restore', 'title' => '还原'],
                            ['name' => 'miniapp/cloud//multi', 'title' => '批量更新'],
                            ['name' => 'miniapp/cloud/getenv', 'title' => '获取云环境信息'],
                        ]
                    ]
                ]
            ]
        ];
        Menu::create($menu);
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete('wechatopen');
        return true;
    }
    
    /**
     * 插件启用方法
     */
    public function enable()
    {
        Menu::enable('wechatopen');
    }

    /**
     * 插件禁用方法
     */
    public function disable()
    {
        Menu::disable('wechatopen');
    }

    /**
     * 安装插件时在 application\extra\addons.php中监听了app_init ,启动时在这里把集成的easywechat SDK 服务放到Container中
     */
    public function appInit()
    {
       // $app = new AppInit();
       // $app->run();
        //
        $apps = [
        'official_account' => OfficialAccount::class,
        'work' => Work::class,
        'mini_program' => MiniProgram::class,
        'payment' => Payment::class,
        ];
        $wechat_default = config('wechat.default') ? config('wechat.default') : [];
        $wechatopenInfo = new wechatopenModel();
        $wechatopenInfoConfig = Cache::get('wechatopen_config');//从上一句初始化时的缓存中获取第三方平台配置
        Container::getInstance()->bind('wechat.open_platform.'.$wechatopenInfoConfig['app_id'], function ($config = [] ) use ($wechatopenInfoConfig,$wechat_default) {
            $wechatopen_app = Container::getInstance()->make(OpenPlatform::class, ['config' => $wechatopenInfoConfig]);
            if ($wechat_default['use_tp_cache']) {
                $wechatopen_app['cache'] = Container::getInstance()->make(CacheBridge::class);
            }
            return $wechatopen_app;
        });
        $appletInfos = Applet::all(); //从数据库获取应用帐号信息
        $appids = array_column($appletInfos,'appid');
        if($appletInfos) {
            $appletInfos = collection($appletInfos)->toArray();
        }
        $applets = array_combine($appids,$appletInfos);

        foreach ($apps as $name => $app) {
            foreach ($applets as $appid => $applet_info) {
                if($applet_info['typedata'] == 'miniapp'){
                    Container::getInstance()->bind('wechat.mini_program.'.$appid, function ($config = [] ) use ($app, $applet_info, $wechat_default) {
                        $config = ['app_id'=>$applet_info['appid'], 'secret' =>$applet_info['appsecret'] , 'token'=> $applet_info['token'], 'aes_key' =>$applet_info['aeskey'], 'wechatapplet_id' =>$applet_info['wechatapplet_id']];
                        //合并配置文件
                        $applet_config = Applet::getAppletConfig($applet_info['appid']);
                        $applet_app = Container::getInstance()->make($app, ['config' => $applet_config]);
                        if ($wechat_default['use_tp_cache']) {
                            $applet_app['cache'] = Container::getInstance()->make(CacheBridge::class);
                        }
                        return $applet_app;
                    });
                }
                if(($applet_info['typedata'] == 'serv_account') || ($applet_info['typedata'] == 'sub_account')){
                    Container::getInstance()->bind('wechat.official_account.'.$appid, function ($config = [] ) use ($app, $applet_info, $wechat_default) {
                        $config = ['app_id'=>$applet_info['appid'], 'secret' =>$applet_info['appsecret'] , 'token'=> $applet_info['token'], 'aes_key' =>$applet_info['aeskey'], 'wechatapplet_id' =>$applet_info['wechatapplet_id']];
                        $applet_config = Applet::getAppletConfig($applet_info['appid']);//array_merge($config,$wechat_default);
                        $applet_app = Container::getInstance()->make($app, ['config' => $applet_config]);
                        if ($wechat_default['use_tp_cache']) {
                            $applet_app['cache'] = Container::getInstance()->make(CacheBridge::class);
                        }
                        return $applet_app;
                    });
                }
                if($applet_info['typedata'] == 'work_account'){
                    Container::getInstance()->bind('wechat.work.'.$appid, function ($config = [] ) use ($app, $applet_info, $wechat_default) {
                        $config = ['app_id'=>$applet_info['appid'], 'secret' =>$applet_info['appsecret'] , 'token'=> $applet_info['token'], 'aes_key' =>$applet_info['aeskey'], 'wechatapplet_id' =>$applet_info['wechatapplet_id']];
                        $applet_config = Applet::getAppletConfig($applet_info['appid']);//array_merge($config,$wechat_default);
                        $applet_app = Container::getInstance()->make($app, ['config' => $applet_config]);
                        if ($wechat_default['use_tp_cache']) {
                            $applet_app['cache'] = Container::getInstance()->make(CacheBridge::class);
                        }
                        return $applet_app;
                    });
                }

            }
            if (isset($applets['default'])) {
                Container::getInstance()->bind('wechat.' . $name, 'wechat.' . $name . '.default');
            }
        }
    }

    /**
     * 顶栏显示当前选中的应用信息
     * @return mixed
     * @throws \Exception
     */
    public function userAppSelect()
    {
        $request = Request::instance();
        $controllername = strtolower($request->controller());
        $actionname = strtolower($request->action());
        $data = [
            'controllername' => $controllername,
            'actionname'     => $actionname
        ];

        return $this->fetch('view/hook/user_app_select', $data);
    }

}
